package tmproject.hlhj.fhp.tmvote.activitys

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.provider.Settings
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.StaggeredGridLayoutManager
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.liaoinstan.springview.container.DefaultHeader
import com.liaoinstan.springview.widget.SpringView
import com.lzy.okgo.OkGo
import com.lzy.okgo.cache.CacheMode
import com.mylhyl.superdialog.SuperDialog
import com.tenma.ventures.share.bean.TMLinkShare
import com.tenma.ventures.share.util.TMShareUtil
import kotlinx.android.synthetic.main.aty_voting.*
import tmproject.hlhj.fhp.tmvote.BaseAty
import tmproject.hlhj.fhp.tmvote.Content
import tmproject.hlhj.fhp.tmvote.R
import tmproject.hlhj.fhp.tmvote.adapters.RuleListAdp
import tmproject.hlhj.fhp.tmvote.adapters.VotingAdp
import tmproject.hlhj.fhp.tmvote.beans.*
import tmproject.hlhj.fhp.tmvote.customView.FullyGridLayoutManager
import tmproject.hlhj.fhp.tmvote.customView.InfoDialog
import tmproject.hlhj.fhp.tmvote.customView.LoadMoreView
import tmproject.hlhj.fhp.tmvote.customView.SearchPop
import tmproject.hlhj.fhp.tmvote.log
import tmproject.hlhj.fhp.tmvote.module.VotingModule
import tmproject.hlhj.fhp.tmvote.network.Urls
import tmproject.hlhj.fhp.tmvote.presenters.VotingPresenter
import tmproject.hlhj.fhp.tmvote.utils.ToastUtil
import tmproject.hlhj.fhp.tmvote.views.VotingView

/**
 * Created by Never Fear   on 2018\8\6 0006.
Never More....
 */
class VotingAty :BaseAty<VotingView,VotingPresenter>(),VotingView, VotingAdp.OnBtVoteClick {

    private lateinit var votingAdp:VotingAdp
    private val datas=ArrayList<PlayerListBean.DataBean.ListBean>()
    private var searchPop:SearchPop?=null
    private var tempBool=true
    private var id=0

    private var page=1;
    private var pageSize=10
    private lateinit var ruleAdp:RuleListAdp
    private val ruleData=ArrayList<String>()
    private var type=0;
    private var emptyView:View?=null

    private var totalNum=0
    private val signUpRule=ArrayList<String>()
    private var avaliableNum=0
    private var canSignUp=  true

    private var voteS=""
    private var voteE=""
    private var signS=""
    private var signE=""
    private var price=""
    private var shareUrl=""
    private var shareTittle=""
    private var shareImg=""
    private var tempb=true
    private var isCreate=false
    private var loadMoreListener:BaseQuickAdapter.RequestLoadMoreListener?=null
    override fun createPresenter(): VotingPresenter {
        return VotingPresenter()
    }

    override fun getContentId(): Int {
        return R.layout.aty_voting
    }

    /*View*/
    override fun initView() {
        /*emptyView*/
        emptyView=LayoutInflater.from(this).inflate(R.layout.empty_view,null)
        emptyView?.findViewById<ImageView>(R.id.img1)
                ?.setImageResource(Content.vote_detail_head_women)
        ToastUtil.context=applicationContext
        /*类型判断*/
        val state = intent.getIntExtra("state", 0)
        if (state==1){
//            ruleLo.visibility=View.VISIBLE
            type=1
            btGoSign.visibility=View.GONE
            tvVoteNum.visibility=View.VISIBLE
            emptyView?.let {
                val loGirl = it.findViewById<LinearLayout>(R.id.loGirl)
                loGirl.visibility=View.GONE
            }
        }else if (state==3){
            type=3
            tvVoteNum.visibility=View.GONE
            btGoSign.visibility=View.GONE
            emptyView?.let {
                val loGirl = it.findViewById<LinearLayout>(R.id.loGirl)
                loGirl.visibility=View.GONE
            }
        }
        else{
            type=2
            tvVoteNum.visibility=View.GONE
//            ruleLo.visibility=View.GONE
            if (intent.getIntExtra("canSign",-1)==0){
                btGoSign.visibility=View.GONE
                emptyView?.let {
                    val loGirl = it.findViewById<LinearLayout>(R.id.loGirl)
                    loGirl.visibility=View.GONE
                }
            }else if (intent.getIntExtra("canSign",-1)==1){
                btGoSign.visibility=View.VISIBLE
                emptyView?.let {
                    val loGirl = it.findViewById<LinearLayout>(R.id.loGirl)
                    loGirl.visibility=View.VISIBLE
                    val textView = it.findViewById<TextView>(R.id.btGoSignUp) as TextView
                    textView.setTextColor(Color.parseColor(Content.shadow_Color))
                    textView.setOnClickListener {
                        val i = Intent(this@VotingAty, SignUpAty::class.java)
                        i.putExtra("id",intent.getIntExtra("id",0))
                        i.putExtra("voteS",voteS)
                        i.putExtra("voteE",voteE)
                        i.putExtra("signS",signS)
                        i.putExtra("signE",signE)
                        i.putExtra("rule",signUpRule)
                        i.putExtra("price",price)

                        startActivity(i)
                    }
                }
            }
        }

        /*使能主题*/
        headBack.setBackgroundResource(Content.vote_detail_head)
        ruleLo.setBackgroundResource(Content.vote_rule_bac)
        votingAdp=VotingAdp(datas,type)
        votingAdp.listener=this
        recyclerview.adapter=votingAdp
        recyclerview.isNestedScrollingEnabled=true
        recyclerview.layoutManager=StaggeredGridLayoutManager(2,LinearLayoutManager.VERTICAL)

        /*规则列表*/
        ruleAdp= RuleListAdp(ruleData)
        ruleList.layoutManager=LinearLayoutManager(this@VotingAty,LinearLayoutManager.VERTICAL,false)
        ruleList.adapter=ruleAdp

        /*上下拉框架*/
        spView.header=DefaultHeader(this@VotingAty)

        loadMoreListener=object :BaseQuickAdapter.RequestLoadMoreListener{
            override fun onLoadMoreRequested() {
                page++
                presenter?.getPlayers(intent.getIntExtra("id",0),page,pageSize,this@VotingAty)
            }
        }
//        votingAdp.setLoadMoreView(LoadMoreView())
        votingAdp.setOnLoadMoreListener(loadMoreListener,recyclerview)
        votingAdp.emptyView = emptyView
    }

    override fun setListener() {
        /*上下拉框架*/
        spView.setListener(object :SpringView.OnFreshListener{
            override fun onRefresh() {
                page=1

                datas.clear()
                presenter?.getPlayers(intent.getIntExtra("id",0),page,pageSize,this@VotingAty)
            }

            override fun onLoadmore() {

            }
        })

        votingAdp.setOnItemClickListener { adapter, view, position ->
            if (tempb){
                tempb=false
                val bundle = Bundle()
                bundle.putString("name",datas[position].competitor_name)
                bundle.putString("num",datas[position].competitor_id.toString())
                bundle.putString("img",Urls.Base_Url+datas[position].avatar)
                bundle.putString("des",datas[position].profile)
                bundle.putString("id",datas[position].competitor_id.toString())
                bundle.putString("rank",(position+1).toString())
                log("fhp","一次")
                if (type!=1){

                    val infoDialog = InfoDialog(this@VotingAty, bundle, 0)
                    infoDialog.show()
                    infoDialog.setOnDismissListener {
                        page=1
                        datas.clear()
                        presenter?.getPlayers(intent.getIntExtra("id",0),page,pageSize,this@VotingAty)
                    }
                }else{
                    val infoDialog = InfoDialog(this@VotingAty, bundle, 1)
                    infoDialog.show()
                    infoDialog.setOnDismissListener {
                        page=1
                        datas.clear()
                        presenter?.getPlayers(intent.getIntExtra("id",0),page,pageSize,this@VotingAty)
                    }
                }

                Thread(Runnable { Thread.sleep(100)
                tempb=true}).start()
            }

        }
        btMore.setOnClickListener {
            val tmLinkShare = TMLinkShare()
            tmLinkShare.thumb=shareImg
            tmLinkShare.description="快来参与投票"
            tmLinkShare.url=shareUrl
            tmLinkShare.title=shareTittle
            TMShareUtil.getInstance(this).shareLink(tmLinkShare)
        }
        btGoSign.setOnClickListener {
            val i = Intent(this@VotingAty, SignUpAty::class.java)
            i.putExtra("id",intent.getIntExtra("id",0))
            i.putExtra("voteS",voteS)
            i.putExtra("voteE",voteE)
            i.putExtra("signS",signS)
            i.putExtra("signE",signE)
            i.putExtra("rule",signUpRule);
            i.putExtra("price",price)
            startActivity(i)
        }
        etSearch.setOnTouchListener { v, event ->
            val drawable = etSearch.getCompoundDrawables()[2]
            if (drawable == null) false;
            //如果不是按下事件，不再处理
            if (event.getAction() != MotionEvent.ACTION_UP)
                 false;
            if (event.getX() > etSearch.getWidth()
                    - etSearch.getPaddingRight()
                    - drawable.getIntrinsicWidth()){
                if (tempBool){
                    if (etSearch.text.isEmpty()){
                        ToastUtil.toast("请输入选手姓名/编号")
                    }else{
                        presenter?.search(intent.getIntExtra("id",0).toString(),etSearch.text.toString(),this@VotingAty)
                    }
                    tempBool=false
                    Thread(Runnable {
                        Thread.sleep(100)
                        tempBool=true
                    }).start()
                }

            }
             false;

        }

    }
    /*详情数据回调*/
    override fun gotVotingData(votingBean: VotingBean) {
        loadingDialog.dismiss()
        val dataBean = votingBean.data
        voteS=dataBean.start_time
        voteE=dataBean.end_time
        signS=dataBean.enroll_start
        signE=dataBean.enroll_end
        tvTittle.text=dataBean.title
        price=dataBean.entry_fee
        if (dataBean.state.equals("1")){

            tvTime.text="活动时间 ：${dataBean.start_time}至${dataBean.end_time}"
        }else{
            tvTime.text="报名 ：${dataBean.enroll_start}至${dataBean.enroll_end}"
        }
        totalNum=dataBean.ballot_number
        avaliableNum=dataBean.user.ballot
        tvVoteNum.text="每人最多可投${totalNum}次，当前可用票数${avaliableNum}"
        log("设置了？")
        if (dataBean.rule!=null){
            ruleData.addAll(dataBean.rule)
        }
        Content.UID=votingBean?.data.user.user_id.toString()
        ruleAdp.notifyDataSetChanged()
        if (dataBean.enroll_rule!=null){
            signUpRule.addAll(dataBean.enroll_rule)
        }
        if (dataBean.is_enroll==1){
            canSignUp=true
        }else{
            canSignUp=false
        }

    }

    override fun logicStart() {
        loadingDialog.show()
        /*获取详情信息*/
        presenter?.getVotingData(intent.getIntExtra("id",0), Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID) ,this)

        presenter?.getPlayers(intent.getIntExtra("id",0),page,pageSize,this@VotingAty)

        presenter?.getShare(intent.getIntExtra("id",0),this@VotingAty)
    }

    /*选手列表数据回调*/
    override fun setPlayerList(playerListBean: PlayerListBean) {
        spView.onFinishFreshAndLoad()
        if (playerListBean.data!=null){
            if (playerListBean.data.list!=null){
                if (playerListBean.data.list.size>0){
                    datas.addAll(playerListBean.data.list)
                    votingAdp.notifyDataSetChanged()
                    if (playerListBean.data.list.size<pageSize){
                        votingAdp.loadMoreEnd()
                    }else{
                        votingAdp.loadMoreComplete()
                    }
                }else{
                    votingAdp.loadMoreEnd()
                }
            }
        }
    }

    override fun getVoteResult(baseBean: BaseBean,p:Int) {
        loadingDialog.dismiss()
        datas[p].ballot=datas[p].ballot+1
        for (i in 0 until p){
            if (datas[p-i].ballot>=datas[p-i-1].ballot){
                var temp=PlayerListBean.DataBean.ListBean()
                temp=datas[p-i-1]
                datas[p-i-1]=datas[p-i]
                datas[p-i]=temp
            }
        }
        avaliableNum=avaliableNum-1
        tvVoteNum.text="每人最多可投${totalNum}次，当前可用票数${avaliableNum}"
        votingAdp.notifyDataSetChanged()
        ToastUtil.toast("投票成功")
    }
    override fun btVoteClick(position: Int) {
        if (type==1){
            SuperDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("确认给“${datas[position].competitor_name}”投一票？")
                    .setPositiveButton("确定"){
                        presenter?.vote(datas[position].competitor_id.toString(),Content.UID,this,position)
                    }
                    .setNegativeButton("取消"){

                    }
                    .build()
        }else{
            val bundle = Bundle()
            bundle.putString("name",datas[position].competitor_name)
            bundle.putString("num",datas[position].competitor_id.toString())
            bundle.putString("img",Urls.Base_Url+datas[position].avatar)
            bundle.putString("des",datas[position].profile)
            bundle.putString("id",datas[position].competitor_id.toString())
            bundle.putString("rank",(position+1).toString())

            val infoDialog = InfoDialog(this@VotingAty, bundle, 0)
            infoDialog.show()
            infoDialog.setOnDismissListener {
                page=1
                datas.clear()
                presenter?.getPlayers(intent.getIntExtra("id",0),page,pageSize,this@VotingAty)
            }
        }

    }

    override fun gotSearchResult(searchBean: SearchBean) {
        loadingDialog.dismiss()
        if (searchBean.data.list.size==0){
            ToastUtil.toast("没有搜索到结果")
            return
        }
            if (null==searchPop){
                searchPop= SearchPop(this@VotingAty,etSearch.width)
            }
            if (searchPop?.isShowing!!){
                searchPop?.dismiss()
                etSearch.setBackgroundResource(R.drawable.search_border)
            }else{
                searchPop?.showAsDropDown(etSearch)
                etSearch.setBackgroundResource(R.drawable.search_border_2)
            }

        searchPop?.setdata(searchBean)

    }
    override fun bindView(): VotingView {
        return this
    }

    override fun setShareUrl(baseBean: ShareBean) {
        loadingDialog.dismiss()
        shareUrl=baseBean.data.url
        shareTittle=baseBean.data.share_title
        shareImg=baseBean.data.image

    }
}